from flask import render_template, redirect, url_for, flash, session
from flask_login import login_user, login_required, current_user

from market import app, db, bcrypt
from market.models import Goods, User
from market.form import RegisterForm, LoginForm


@app.route('/')
@app.route('/home')
def index():
    return render_template('home.html')


@login_required
@app.route('/goods')
def goods_page():
    items = Goods.query.all()
    print(current_user.username)
    return render_template('goods.html', items=items)


@app.route('/registration', methods=['GET', 'POST'])
def registration_page():
    form = RegisterForm()
    if form.validate_on_submit():
        password_hash = bcrypt.generate_password_hash(form.password1.data).decode('utf-8')
        user_to_create = User(username=form.username.data,
                              password_hash=password_hash)
        with app.app_context():
            db.session.add(user_to_create)
            db.session.commit()
            login_user(user_to_create)
            flash('You are now registered!', 'success')
            return redirect(url_for('goods_page'))
    if form.errors != {}:
        for err_msg in form.errors.values():
            flash(f'There was an error with creating a user: {err_msg}', category='error')
    return render_template('registration.html', form=form)


@app.route('/login', methods=['GET', 'POST'])
def login_page():
    form = LoginForm()
    attempted_user = User.query.filter_by(username=form.username.data).first()
    if attempted_user and attempted_user.check_password_correction(
            attempted_password=form.password.data):
        login_user(attempted_user)
        flash('You are now logged in', category='success')
        return redirect(url_for('goods_page'))
    else:
        flash('Username and password are not match', category='info')
    return render_template('login.html', form=form)
